package com.asen.test.viewmodel

import androidx.lifecycle.MutableLiveData
import com.asen.app.info.Produce
import com.asen.app.info.User
import com.asen.libcommon.base.viewbind.BaseViewModel
import java.util.concurrent.ConcurrentHashMap


/**
 * @date   : 2021/2/23
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : 测试用例
 */
class ViewBindModel : BaseViewModel() {

    // TODO:构造函数（在 ViewModelProvider 里通过 class.newInstance 创建实例）
    private val maps: MutableMap<String?, MutableLiveData<*>>? = ConcurrentHashMap() // TODO: 初始化集合(线程安全)

    val mUserLiveData = get(User::class.java)

    val mProduceLiveData = get(Produce::class.java)

    /**
     * 通过指定的数据实体类获取对应的MutableLiveData类
     * @param clazz 传递过来的数据类 info
     */
    protected fun <T> get(clazz: Class<T>): MutableLiveData<T> = get(null, clazz)

    /**
     * 通过指定的key或者数据实体类获取对应的MutableLiveData类
     * @param key
     * @param clazz 传递过来的数据类 info
     */
    protected fun <T> get(key: String?, clazz: Class<T>): MutableLiveData<T> {

        val keyName: String? = key ?: clazz.canonicalName

        var mutableLiveData: MutableLiveData<T>? = (maps?.get(keyName) as MutableLiveData<T>?)
        //1.判断集合是否已经存在livedata对象
        if (mutableLiveData != null) return mutableLiveData

        //2.如果集合中没有对应实体类的Livedata对象，就创建并添加至集合中
        mutableLiveData = MutableLiveData()
        maps?.set(keyName, mutableLiveData)

        return mutableLiveData
    }

    /**
     * 在对应的FragmentActivity销毁之后调用
     */
    override fun onCleared() {
        super.onCleared()
        maps?.clear()
    }
}